package com.ych.modules.api.authorInfc.jackpot.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ych.modules.api.authorInfc.jackpot.service.JackpotService;
import com.ych.modules.base.dbEntity.*;
import com.ych.modules.base.service.*;
import com.ych.rabbitmq.exchange.RaffleTicketJackpotExchange;
import com.ych.utils.DateUtils;
import com.ych.utils.TLMap;
import com.ych.utils.UUID;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2021/3/15
 * Time: 16:59
 * Description:
 */
@Service
public class JackpotServiceImpl implements JackpotService {
    @Autowired
    private ITRaffleTicketJackpotService itRaffleTicketJackpotService;
    @Autowired
    private ITUserRaffleTicketService    itUserRaffleTicketService;
    @Autowired
    private ITUserAccountService         itUserAccountService;
    @Autowired
    private ITUserAccountChangeService   itUserAccountChangeService;
    @Autowired
    private ITUserJobService             itUserJobService;
    @Autowired
    private ITUserItemService            itUserItemService;
    @Autowired
    private ITItemShowOrderService       itItemShowOrderService;
    @Autowired
    private ITSysJackpotRatioService     itSysJackpotRatioService;
    @Autowired
    private ITSysJackpotAmountLogService itSysJackpotAmountLogService;
    @Autowired
    private RabbitTemplate               rabbitTemplate;

    @Override
    public void addJackpot(TRaffleTicketJackpotEntity entity) {
        if (null == entity.getLotteryTime()
                || null == entity.getLatestPurchaseTime()) {
            throw new RuntimeException("必传参数为空");
        }
        if (entity.getLatestPurchaseTime().getTime() > entity.getLotteryTime().getTime()) {
            throw new RuntimeException("最后购买时间不能大于开奖时间");
        }
        entity.setJackpotId(UUID.randomUUID());
        entity.setUserId(TLMap.getUserId());
        entity.setAmount(BigDecimal.ZERO);//初始化为0
        entity.setCreateTime(new Date());
        entity.setIssueCode(DateUtils.format(entity.getLotteryTime(), "yyyyMMdd"));//不重复
        entity.setLotteryNumber(null);
        entity.setJackpotStatusType("10011001");//待开奖
        itRaffleTicketJackpotService.insert(entity);
        //加入延迟队列定时任务
        //发送延时消息，延时处理订单
        rabbitTemplate.convertAndSend(RaffleTicketJackpotExchange.EXCHANGE_NAME, RaffleTicketJackpotExchange.QUEUE_NAME, entity.getJackpotId(),
                message -> {
                    //开奖时间减去当前时间的毫秒数，再加上50毫秒给程序处理算法
                    Long delayTimes = entity.getLotteryTime().getTime() - new Date().getTime();
                    //TODO 测试使用，改为十分钟后开奖
                    delayTimes = DateUtils.addDateMinutes(new Date(), 10).getTime();//十分钟后开奖
                    message.getMessageProperties().setHeader("x-delay", delayTimes + 50);//转为毫秒
                    return message;
                });
    }

    @Override
    public void amountIncrease(String jackpotId, BigDecimal amount) {
        Wrapper<TRaffleTicketJackpotEntity> wrapper = new EntityWrapper<TRaffleTicketJackpotEntity>()
                .where("1=1")
                .eq("jackpot_id", jackpotId);
        //金额自增
        itRaffleTicketJackpotService.updateForSet("amount = amount+(" + amount + ")", wrapper);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void applyJackpot(TUserRaffleTicketEntity ticketEntity) {
        TRaffleTicketJackpotEntity jackpotEntity = itRaffleTicketJackpotService.selectById(ticketEntity.getJackpotId());
        if (null == jackpotEntity) {
            throw new RuntimeException("目标活动不存在");
        }
        if (new Date().getTime() > jackpotEntity.getLatestPurchaseTime().getTime()) {
            throw new RuntimeException("该奖池报名时间已结束");
        }
        ticketEntity.setTicketId(UUID.randomUUID());
        ticketEntity.setUserId(TLMap.getUserId());
        ticketEntity.setIsChecked("1");//没有兑换
        ticketEntity.setCodeInit("0");//已经设置了兑换码
        ticketEntity.setCreateTime(new Date());
        itUserRaffleTicketService.insert(ticketEntity);
        //添加抽奖券变更记录
        this.addAccountRaffleTicketInfo(ticketEntity);
    }

    @Override
    public TRaffleTicketJackpotEntity getJackpot(String jackpotId) {
        TRaffleTicketJackpotEntity entity = itRaffleTicketJackpotService.selectById(jackpotId);
        Wrapper<TUserRaffleTicketEntity> wrapper = new EntityWrapper<TUserRaffleTicketEntity>()
                .where("1=1")
                .eq("jackpot_id", jackpotId);
        List<TUserRaffleTicketEntity> list = itUserRaffleTicketService.selectList(wrapper);
        entity.setRaffleTicketList(list);
        return entity;
    }

    @Override
    public TRaffleTicketJackpotEntity getCurrentJackpot() {
        //取没有开奖的第一个，开奖时间最近的那一个
        Wrapper<TRaffleTicketJackpotEntity> wrapper = new EntityWrapper<TRaffleTicketJackpotEntity>()
                .where("1=1")
                .eq("jackpot_status_type", "10011001")
//                .and("date_format(lottery_time,'%Y-%m-%d') <= date_format(CURDATE(),'%Y-%m-%d')")
                .orderBy("lottery_time asc");
        List<TRaffleTicketJackpotEntity> list = itRaffleTicketJackpotService.selectList(wrapper);
        if (null == list || list.size() == 0) {
            return null;
        }
        TRaffleTicketJackpotEntity entity = list.get(0);
        //查询上一期开奖信息
        wrapper = new EntityWrapper<TRaffleTicketJackpotEntity>()
                .where("1=1")
                .eq("jackpot_status_type", "10011002")
                .orderBy("lottery_time desc");
        list = itRaffleTicketJackpotService.selectList(wrapper);
        if (null != list && list.size() > 0) {
            TRaffleTicketJackpotEntity lastEntity = list.get(0);
            entity.setLastIssueCode(lastEntity.getIssueCode());
            entity.setLastLotteryNumber(lastEntity.getLotteryNumber());
        }
        //扩展当前用户投注数量
        this.extendCurrentUserBetNum(entity);
        return entity;
    }

    @Override
    public void addAmountToJackpot(String chargeBusinessType, BigDecimal amount, String businessId, String jackpotId) {
        TSysJackpotAmountLogEntity logEntity;
        switch (chargeBusinessType) {
            case "10012001"://项目发布
                logEntity = this.itemToJackpot(chargeBusinessType, amount, businessId);
                break;
            case "10012002"://任务发布
                logEntity = this.jobToJackpot(chargeBusinessType, amount, businessId);
                break;
            case "10012003"://首页轮播
                logEntity = this.carouselToJackpot(chargeBusinessType, amount, businessId);
                break;
            case "10012004"://固定头条
                logEntity = this.headlineToJackpot(chargeBusinessType, amount, businessId);
                break;
            case "10012005"://jackpot上一个奖池继承
                logEntity = new TSysJackpotAmountLogEntity();
                logEntity.setAmount(amount);
                logEntity.setBusinessId(businessId);
                logEntity.setStatus("0");//正常
                logEntity.setChargeBusinessType(chargeBusinessType);
                break;
            default://未知类型，直接返回不管了
                return;
        }
        logEntity.setId(UUID.randomUUID());
        logEntity.setCreateTime(new Date());
        if (StringUtils.isBlank(jackpotId)) {
            TRaffleTicketJackpotEntity jackpotEntity = this.getCurrentJackpot();
            jackpotId = jackpotEntity.getJackpotId();
        }
        logEntity.setJackpotId(jackpotId);
        itSysJackpotAmountLogService.insert(logEntity);
        //奖池金额增加
        this.amountIncrease(jackpotId, logEntity.getAmount());
    }

    /**
     * 6位对应全中为特等奖，5位对应中为一等奖，4位对应中为二等奖，3位对应中为三等奖，
     * 四个奖，各加权平均分总奖金池的20% 剩下的20%留于奖池中
     *
     * @param jackpotId 奖池编号
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void runLottery(String jackpotId) {
        TRaffleTicketJackpotEntity jackpotEntity = itRaffleTicketJackpotService.selectById(jackpotId);
        if (null == jackpotEntity) {
            throw new RuntimeException("奖池不存在！");
        }
        //当前时间小于开奖时间，不能开奖
        if (new Date().getTime() < jackpotEntity.getLotteryTime().getTime()) {
            throw new RuntimeException("未到开奖时间不能开奖");
        }
        //10011001:待开奖  不为待开奖则不能开奖
        if (!"10011001".equals(jackpotEntity.getJackpotStatusType())) {
            throw new RuntimeException("奖池不为待开奖状态");
        }
        //开奖随机数生成
        String lottyNum = String.valueOf(this.getLottyRandomNum());
        jackpotEntity.setLotteryNumber(lottyNum);
        List<TUserRaffleTicketEntity> ticketEntityList = this.getCurrentJackpotTicketList(jackpotEntity.getJackpotId());
        BigDecimal nextJackpotRate = new BigDecimal("0.2");//当前奖池进入下一个奖池的金额比例，初始化为百分之二十
        //奖池没有参加抽奖的奖券，则直接退出
        if (null == ticketEntityList || ticketEntityList.size() == 0) {
            //将奖池金额继承到下一个奖池
            nextJackpotRate = new BigDecimal("1");//百分之百，全部分给下一个奖池
            //创建下一个奖池并且继承当前奖池金额到下一个。
            this.extendsCurrentJackpotToNext(jackpotEntity, nextJackpotRate);
            return;
        }
        //特等奖每份金额,颁奖并且返回每份分红金额
        BigDecimal bestPeerAmount = this.rewardBestAward(jackpotEntity, lottyNum);
        if (bestPeerAmount.compareTo(BigDecimal.ZERO) == 0) {
            nextJackpotRate = nextJackpotRate.add(new BigDecimal("0.2"));
        }
        //一等奖每份金额
        BigDecimal firstPeerAmount = this.rewardOtherAward(ticketEntityList, jackpotEntity, lottyNum, 5);
        if (firstPeerAmount.compareTo(BigDecimal.ZERO) == 0) {
            nextJackpotRate = nextJackpotRate.add(new BigDecimal("0.2"));
        }
        //二等奖每份金额
        BigDecimal secondPeerAmount = this.rewardOtherAward(ticketEntityList, jackpotEntity, lottyNum, 4);
        if (secondPeerAmount.compareTo(BigDecimal.ZERO) == 0) {
            nextJackpotRate = nextJackpotRate.add(new BigDecimal("0.2"));
        }
        //三等奖每份金额
        BigDecimal thirdPeerAmount = this.rewardOtherAward(ticketEntityList, jackpotEntity, lottyNum, 3);
        if (thirdPeerAmount.compareTo(BigDecimal.ZERO) == 0) {
            nextJackpotRate = nextJackpotRate.add(new BigDecimal("0.2"));
        }
        //创建下一个奖池并且继承当前奖池金额到下一个。
        this.extendsCurrentJackpotToNext(jackpotEntity, nextJackpotRate);
    }

    /**
     * 创建下一个奖池并且继承当前奖池金额到下一个。
     *
     * @param jackpotEntity
     * @param nextJackpotRate
     */
    private void extendsCurrentJackpotToNext(TRaffleTicketJackpotEntity jackpotEntity, BigDecimal nextJackpotRate) {
        BigDecimal amount = jackpotEntity.getAmount();
        //上一个奖池状态置为已经开奖
        jackpotEntity.setJackpotStatusType("10011002");//已经开奖
        jackpotEntity.setAmount(BigDecimal.ZERO);//清空奖池
        itRaffleTicketJackpotService.updateById(jackpotEntity);
        //开启下一个奖池 10001009:奖池jackpot表
        TRaffleTicketJackpotEntity ticketJackpotEntity = new TRaffleTicketJackpotEntity();
        ticketJackpotEntity.setLotteryTime(DateUtils.addDateDays(jackpotEntity.getLotteryTime(), 7));//上一个奖池开奖七天后
        ticketJackpotEntity.setLatestPurchaseTime(DateUtils.addDateHours(ticketJackpotEntity.getLotteryTime(), -1));//开奖时间前一个小时停止购买
        //TODO 设置下一个开奖时间为10分钟后
        ticketJackpotEntity.setLotteryTime(DateUtils.addDateMinutes(jackpotEntity.getLotteryTime(), 10));
        ticketJackpotEntity.setLatestPurchaseTime(DateUtils.addDateMinutes(ticketJackpotEntity.getLatestPurchaseTime(), 10));
        this.addJackpot(ticketJackpotEntity);
        this.addAmountToJackpot("10012005", amount.multiply(nextJackpotRate), jackpotEntity.getJackpotId(), null);
    }

    /**
     * 分发特等奖以外的奖励
     *
     * @param ticketEntityList
     * @param jackpotEntity
     * @param lottyNum
     * @param matchNum
     * @return
     */
    private BigDecimal rewardOtherAward(List<TUserRaffleTicketEntity> ticketEntityList, TRaffleTicketJackpotEntity jackpotEntity, String lottyNum, int matchNum) {
        BigDecimal peerAmount = this.getOtherPeerAmount(ticketEntityList, jackpotEntity, lottyNum, matchNum);
        List<TUserRaffleTicketEntity> list = this.getRewardTicketList(ticketEntityList, lottyNum, matchNum);
        for (TUserRaffleTicketEntity entity : list) {
            this.rewardTicket(entity, peerAmount);
        }
        return peerAmount;
    }

    /**
     * 特等奖分发
     *
     * @param jackpotEntity
     * @param lottyNum
     * @return
     */
    private BigDecimal rewardBestAward(TRaffleTicketJackpotEntity jackpotEntity, String lottyNum) {
        BigDecimal bestPeerAmount = this.getBestPeerAmount(jackpotEntity, lottyNum);
        Wrapper<TUserRaffleTicketEntity> wrapper = new EntityWrapper<TUserRaffleTicketEntity>()
                .where("1=1")
                .eq("jackpot_id", jackpotEntity.getJackpotId())
                .eq("code_init", "0")
                .eq("redeem_code", lottyNum);//奖池码完全相同
        List<TUserRaffleTicketEntity> list = itUserRaffleTicketService.selectList(wrapper);
        for (TUserRaffleTicketEntity entity : list) {
            this.rewardTicket(entity, bestPeerAmount);
        }
        return bestPeerAmount;
    }

    /**
     * 奖券兑换分发中奖金币
     *
     * @param entity     奖券实体
     * @param peerAmount 每份中奖金额
     */
    private void rewardTicket(TUserRaffleTicketEntity entity, BigDecimal peerAmount) {
        entity.setIsChecked("0");//已经兑换奖券
        entity.setBrokerageAmount(peerAmount);
        itUserRaffleTicketService.updateById(entity);
        //抽奖券使用订单:10001007
        itUserAccountService.alterGoldCoinAmount("10000001", "10001007", entity.getUserId(), entity.getTicketId(), peerAmount);
    }

    /**
     * 获取其他奖项每份金额
     * 奖券数字匹配数量，6：特等奖 5：一等奖 4：二等奖 3：三等奖
     *
     * @param ticketEntityList
     * @param jackpotEntity
     * @param lottyNum
     * @return
     */
    private BigDecimal getOtherPeerAmount(List<TUserRaffleTicketEntity> ticketEntityList, TRaffleTicketJackpotEntity jackpotEntity, String lottyNum, int matchNum) {
        List<TUserRaffleTicketEntity> firstTicketList = this.getRewardTicketList(ticketEntityList, lottyNum, matchNum);
        if (firstTicketList.size() == 0) {
            return BigDecimal.ZERO;
        }
        BigDecimal peerAmount = this.getJackpotLottyAmount(jackpotEntity, firstTicketList.size());
        return peerAmount;
    }

    /**
     * 获取中奖的奖券集合
     *
     * @param ticketEntityList
     * @param lottyNum
     * @param matchNum
     * @return
     */
    private List<TUserRaffleTicketEntity> getRewardTicketList(List<TUserRaffleTicketEntity> ticketEntityList, String lottyNum, int matchNum) {
        List<TUserRaffleTicketEntity> ticketList = new ArrayList<>();
        //奖券数字匹配数量，6：特等奖 5：一等奖 4：二等奖 3：三等奖
        int ticketLevel;
        for (TUserRaffleTicketEntity ticketEntity : ticketEntityList) {
            //获取中奖数量
            ticketLevel = this.getRaffleTicketLottyLevel(ticketEntity, lottyNum);
            //匹配了次数则放入集合
            if (ticketLevel == matchNum) {
                ticketList.add(ticketEntity);
            }
        }
        return ticketList;
    }

    /**
     * 获取中间数字数量
     *
     * @param ticketEntity
     * @param lottyNum
     * @return
     */
    private int getRaffleTicketLottyLevel(TUserRaffleTicketEntity ticketEntity, String lottyNum) {
        String[] lottyNumArr = lottyNum.split("");
        String[] redeemCodeArr = ticketEntity.getRedeemCode().split("");
        int matchCount = 0;
        for (int i = 0; i < lottyNum.length(); i++) {
            if (lottyNumArr[i].equals(redeemCodeArr[i])) {
                matchCount++;
            }
        }
        return matchCount;
    }


    /**
     * 获取当前奖池的奖券集合
     *
     * @param jackpotId
     * @return
     */
    private List<TUserRaffleTicketEntity> getCurrentJackpotTicketList(String jackpotId) {
        Wrapper<TUserRaffleTicketEntity> wrapper = new EntityWrapper<TUserRaffleTicketEntity>()
                .where("1=1")
                .eq("jackpot_id", jackpotId)
                .eq("code_init", "0")
                .eq("is_checked", "1");//未开奖
        return itUserRaffleTicketService.selectList(wrapper);
    }

    /**
     * 获取特等奖每份奖金
     *
     * @param jackpotEntity
     * @param lottyNum      开奖号码
     * @return
     */
    private BigDecimal getBestPeerAmount(TRaffleTicketJackpotEntity jackpotEntity, String lottyNum) {
        Wrapper<TUserRaffleTicketEntity> wrapper = new EntityWrapper<TUserRaffleTicketEntity>()
                .where("1=1")
                .eq("jackpot_id", jackpotEntity.getJackpotId())
                .eq("code_init", "0")
                .eq("redeem_code", lottyNum);//奖池码完全相同
        int count = itUserRaffleTicketService.selectCount(wrapper);
        if (count == 0) {
            return BigDecimal.ZERO;
        }
        BigDecimal peerAmount = this.getJackpotLottyAmount(jackpotEntity, count);
        return peerAmount;
    }

    /**
     * 获取奖池每份分奖金额
     *
     * @param jackpotEntity 奖池实体
     * @param count         中奖数量
     * @return
     */
    private BigDecimal getJackpotLottyAmount(TRaffleTicketJackpotEntity jackpotEntity, int count) {
        return jackpotEntity.getAmount()
                .multiply(new BigDecimal("0.2"))
                .divide(new BigDecimal(String.valueOf(count)));
    }

    /**
     * 开奖随机数获取
     *
     * @return
     */
    private int getLottyRandomNum() {
        return (int) ((Math.random() * 9 + 1) * 100000);
    }

    /**
     * 固定头条任务发布金额到奖池
     *
     * @param chargeBusinessType
     * @param amount
     * @param businessId
     * @return
     */
    private TSysJackpotAmountLogEntity headlineToJackpot(String chargeBusinessType, BigDecimal amount, String businessId) {
        TSysJackpotAmountLogEntity logEntity = new TSysJackpotAmountLogEntity();
        try {
            TItemShowOrderEntity orderEntity = itItemShowOrderService.selectById(businessId);
            if (null == orderEntity) {
                throw new RuntimeException("固定头条任务不存在");
            }
            //获取写入奖池比例
            BigDecimal rate = this.getRatio(chargeBusinessType);
            BigDecimal goldAmount = amount.multiply(rate);
            logEntity.setAmount(goldAmount);
            logEntity.setBusinessId(businessId);
            logEntity.setStatus("0");
            logEntity.setChargeBusinessType(chargeBusinessType);
        } catch (Exception e) {
            logEntity.setStatus("1");
            logEntity.setLog(e.getMessage());
        } finally {
            return logEntity;
        }
    }

    /**
     * 轮播任务发布金额到奖池
     *
     * @param chargeBusinessType
     * @param amount
     * @param businessId
     * @return
     */
    private TSysJackpotAmountLogEntity carouselToJackpot(String chargeBusinessType, BigDecimal amount, String businessId) {
        TSysJackpotAmountLogEntity logEntity = new TSysJackpotAmountLogEntity();
        try {
            TItemShowOrderEntity orderEntity = itItemShowOrderService.selectById(businessId);
            if (null == orderEntity) {
                throw new RuntimeException("轮播任务不存在");
            }
            //获取写入奖池比例
            BigDecimal rate = this.getRatio(chargeBusinessType);
            BigDecimal goldAmount = amount.multiply(rate);
            logEntity.setAmount(goldAmount);
            logEntity.setBusinessId(businessId);
            logEntity.setStatus("0");
            logEntity.setChargeBusinessType(chargeBusinessType);
        } catch (Exception e) {
            logEntity.setStatus("1");
            logEntity.setLog(e.getMessage());
        } finally {
            return logEntity;
        }
    }

    /**
     * 任务发布金额到奖池
     *
     * @param chargeBusinessType
     * @param amount
     * @param businessId
     * @return
     */
    private TSysJackpotAmountLogEntity jobToJackpot(String chargeBusinessType, BigDecimal amount, String businessId) {
        TSysJackpotAmountLogEntity logEntity = new TSysJackpotAmountLogEntity();
        try {
            TUserJobEntity jobEntity = itUserJobService.selectById(businessId);
            if (null == jobEntity) {
                throw new RuntimeException("任务不存在");
            }
            //获取写入奖池比例
            BigDecimal rate = this.getRatio(chargeBusinessType);
            BigDecimal goldAmount = amount.multiply(rate);
            logEntity.setAmount(goldAmount);
            logEntity.setBusinessId(businessId);
            logEntity.setStatus("0");
            logEntity.setChargeBusinessType(chargeBusinessType);
        } catch (Exception e) {
            logEntity.setStatus("1");
            logEntity.setLog(e.getMessage());
        } finally {
            return logEntity;
        }
    }

    /**
     * 项目发布金额到奖池
     *
     * @param chargeBusinessType
     * @param amount
     * @param businessId
     * @return
     */
    private TSysJackpotAmountLogEntity itemToJackpot(String chargeBusinessType, BigDecimal amount, String businessId) {
        TSysJackpotAmountLogEntity logEntity = new TSysJackpotAmountLogEntity();
        try {
            TUserItemEntity itemEntity = itUserItemService.selectById(businessId);
            if (null == itemEntity) {
                throw new RuntimeException("项目不存在");
            }
            //获取写入奖池比例
            BigDecimal rate = this.getRatio(chargeBusinessType);
            BigDecimal goldAmount = amount.multiply(rate);
            logEntity.setAmount(goldAmount);
            logEntity.setBusinessId(businessId);
            logEntity.setStatus("0");
            logEntity.setChargeBusinessType(chargeBusinessType);
        } catch (Exception e) {
            logEntity.setStatus("1");
            logEntity.setLog(e.getMessage());
        } finally {
            return logEntity;
        }
    }

    /**
     * 获取写入奖池比例
     *
     * @param chargeBusinessType
     * @return
     */
    private BigDecimal getRatio(String chargeBusinessType) {
        Wrapper<TSysJackpotRatioEntity> wrapper = new EntityWrapper<TSysJackpotRatioEntity>()
                .where("1=1")
                .eq("charge_business_type", chargeBusinessType);
        TSysJackpotRatioEntity entity = itSysJackpotRatioService.selectOne(wrapper);
        return entity.getRate();
    }

    /**
     * 扩展当前用户投注数量
     *
     * @param entity
     */
    private void extendCurrentUserBetNum(TRaffleTicketJackpotEntity entity) {
        Wrapper<TUserRaffleTicketEntity> wrapper = new EntityWrapper<TUserRaffleTicketEntity>()
                .where("1=1")
                .eq("user_id", TLMap.getUserId())
                .eq("jackpot_id", entity.getJackpotId());
        int count = itUserRaffleTicketService.selectCount(wrapper);
        entity.setCurrentUserBetNum(count);
    }

    /**
     * 添加优惠券变更记录
     *
     * @param ticketEntity
     */
    private void addAccountRaffleTicketInfo(TUserRaffleTicketEntity ticketEntity) {
        TUserAccountEntity accountEntity = itUserAccountService.selectById(ticketEntity.getUserId());
        if (accountEntity.getRaffleTicket() < 1) {
            throw new RuntimeException("抽奖券不足");
        }
        TUserAccountChangeEntity changeEntity = new TUserAccountChangeEntity();
        changeEntity.setChangeId(UUID.randomUUID());
        changeEntity.setUserId(accountEntity.getUserId());
        changeEntity.setAccountTrend("10000002");//支出
        changeEntity.setBusinessId(ticketEntity.getTicketId());
        changeEntity.setAccountChangeBusinessType("10001007");//抽奖券使用订单
        //现金
        changeEntity.setCashAmount(BigDecimal.ZERO);
        changeEntity.setBeforeCashAmount(accountEntity.getCashAmount());
        changeEntity.setAfterCashAmount(accountEntity.getCashAmount());
        //金币
        changeEntity.setGoldCoinAmount(BigDecimal.ZERO);
        changeEntity.setBeforeCashAmount(accountEntity.getGoldCoinAmount());
        changeEntity.setAfterGoldCoinAmount(accountEntity.getGoldCoinAmount());
        //抽奖券
        changeEntity.setRaffleTicket(1);
        changeEntity.setBeforeRaffleTicket(accountEntity.getRaffleTicket());
        changeEntity.setAfterRaffleTicket(accountEntity.getRaffleTicket() - 1);
        changeEntity.setCreateTime(new Date());
        itUserAccountChangeService.insert(changeEntity);
        //账户抽奖券-1减去
        TUserAccountEntity tempAccountEntity = new TUserAccountEntity();
        tempAccountEntity.setUserId(accountEntity.getUserId());
        tempAccountEntity.setRaffleTicket(-1);//使用一张抽奖券
        itUserAccountService.updateByEntity(tempAccountEntity);
    }
}
